﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using System.Web.Mvc;
using System;
using System.Xml;
using ThirdPrize.Classes;
using ThirdPrize.Models;

namespace ThirdPrize.Controllers
{
    public class NurbsController : Controller
    {
        //
        // GET: /Nurbs/
        private readonly euzycdrv_ThirdPrizeEntities _entities = new euzycdrv_ThirdPrizeEntities();
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("Application");

        /// <summary>
        /// Index page
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            log.Info("Nurbs Index Visited");

            int? comicNo = GetMax();

            return RedirectToAction("ShowComic", new { comicNo });
        }

        private int GetMax()
        {
            DbSet<Comic> ac = _entities.Comics;

            int comicNo = ac.Max(p => p.ComicNo);

            return comicNo;
        }

        /// <summary>
        /// ShowComic page
        /// </summary>
        /// <param name="comicNo"></param>
        /// <returns></returns>
        public ActionResult ShowComic(int? comicNo)
        {
            log.Info(String.Format("Nurbs ShowComic Visited - {0}", comicNo));

            if (comicNo.HasValue)
            {
                var model = GetModelForComicNo(comicNo);
                
                return View(model);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        /// <summary>
        /// ShowComic page
        /// </summary>
        /// <param name="comicNo"></param>
        /// <returns></returns>
        public ActionResult Archive()
        {
            log.Info("Nurbs ShowComic Visited");

            var cl = GetComicListModel(1);

            return View(cl);
        }

        /// <summary>
        /// About page
        /// </summary>
        /// <returns></returns>
        public ActionResult About()
        {
            return View();
        }

        /// <summary>
        /// get the post back from the drop down list
        /// and forward to ShowComic
        /// </summary>
        /// <param name="comicNo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ComicSelected(int comicNo)
        {
            return RedirectToAction("ShowComic", new {comicNo});
        }

        private ComicModel GetModelForComicNo(int? comicNo)
        {
            DbSet<Comic> ac = _entities.Comics;
            var comicModel = new ComicModel();
            string comicNoString=comicNo.Value.ToString(CultureInfo.InvariantCulture);

            int max = GetMax();

            var allTitles = new List<SelectListItem>();
            foreach (var comic in ac)
            {
                var item = new SelectListItem();
                item.Value = comic.ComicNo.ToString(CultureInfo.InvariantCulture);
                item.Selected = (item.Value == comicNoString);
                item.Text = comic.Title;
                allTitles.Add(item);
            }

            Comic theComic = ac.FirstOrDefault(c => c.ComicNo == comicNo);

            switch (theComic.ImageType)
            {
                case 0:
                    comicModel.ImageSuffix = "jpg";
                    break;
                case 1:
                    comicModel.ImageSuffix = "png";
                    break;
                case 2:
                    comicModel.ImageSuffix = "gif";
                    break;

                default:
                    break;
            }
            comicModel.CurrentEpisode = comicNo;
            comicModel.NoPanels = (int) theComic.NoPanels;
            comicModel.Title = theComic.Title;
            comicModel.AltText = theComic.AltText;
            comicModel.Comment = theComic.Comment;
            comicModel.PublishDate = (theComic.PublishDate  == null ? new DateTime(2004,1,1) : (DateTime)theComic.PublishDate);
            comicModel.isFirst = (comicNo == 1);
            comicModel.isLast = (comicNo == max);
            comicModel.LastComic = allTitles.Count;

            var path = Path.Combine(Server.MapPath("~/Images/Nurbs/"), String.Format("{0}-1.{1}",comicModel.CurrentEpisode, comicModel.ImageSuffix));
            if (System.IO.File.Exists(path))
            {
                Bitmap img = new Bitmap(path);

                comicModel.ImageHeighth = img.Height;
                comicModel.ImageWidth = img.Width;
            }
            else
            {
                comicModel.ImageHeighth = 10;
                comicModel.ImageWidth = 10;
            }

            return comicModel;
        }

        #region Nurbs

        public ActionResult ComicList(int? episodeToEdit)
        {
            var cl = GetComicListModel(episodeToEdit);

            return View(cl);
        }

        private ComicListModel GetComicListModel(int? episodeToEdit)
        {
            DbSet<Comic> ac = _entities.Comics;

            ComicListModel cl = new ComicListModel();

            cl.AllEpisodes = ac.ToList();
            cl.AllEpisodes.Reverse();

            if (episodeToEdit.HasValue)
            {
                Comic c = ac.FirstOrDefault(cc => cc.ComicNo == episodeToEdit);

                cl.ComicNo = c.ComicNo;
                cl.Title = c.Title;
                cl.Comment = c.Comment;
                cl.NoPanels = c.NoPanels;
                cl.AltText = c.AltText;
                cl.ImageType = c.ImageType;
                cl.PublishDate = c.PublishDate;
            }
            return cl;
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult UpdateEpisode(string comicNo, string noPanels, string title, string comment, string altText, int imageType, DateTime publishDate)
        {
            ComicEdit ce = new ComicEdit();

            ce.AddOrUpdate(Int32.Parse(comicNo), Int32.Parse(noPanels), title, comment, altText, imageType, publishDate);
            WriteRssFeed();
            return RedirectToAction("ComicList");
        }

        public ActionResult DeleteEpisode(int? episodeToDelete)
        {
            ComicEdit ce = new ComicEdit();

            ce.Delete(episodeToDelete);
            WriteRssFeed();
            return RedirectToAction("ComicList");
        }

        [HttpPost]
        public ActionResult UploadImages(IEnumerable<HttpPostedFileBase> files)
        {

            foreach (var file in files)
            {
                if (file != null)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/Nurbs"), fileName);
                    file.SaveAs(path);
                }
            }
            return RedirectToAction("ComicList");
        }

        void WriteRssFeed()
        {
            SyndicationFeed feed = new SyndicationFeed();
            feed.Title = new TextSyndicationContent("The Nurbs");
            feed.Copyright = new TextSyndicationContent("Shaun Pryszlak");
            feed.Description = new TextSyndicationContent("A web comic.  Updated occasionally.");
            feed.LastUpdatedTime = DateTime.Now;

            var lastTen = _entities.Comics.ToList().GetRange(_entities.Comics.Count() - 10, 10);
            lastTen.Reverse();

            List<SyndicationItem> items = new List<SyndicationItem>();

            foreach (var comic in lastTen)
            {
                SyndicationItem item = new SyndicationItem();
                if (comic.PublishDate != null) item.PublishDate = (DateTimeOffset)comic.PublishDate;
                item.Title = new TextSyndicationContent(comic.Title);
                item.Links.Add(new SyndicationLink(new Uri(String.Format("http://www.thirdprize.org/Nurbs/ShowComic?comicNo={0}", comic.ComicNo)), "Dunno", comic.Title, "text/html", 1000));
                items.Add(item);
            }
            feed.Items = items;
            string path = Path.Combine(Server.MapPath("~"), "NurbsFeed.xml");

            XmlWriter xmlWriter = XmlWriter.Create(path);
            feed.SaveAsRss20(xmlWriter);
            xmlWriter.Dispose();
        }
        #endregion

    }
}
